package com.xuchang.service.impl;

import com.wf.captcha.utils.CaptchaUtil;
import com.xuchang.Feign.JwtToken;
import com.xuchang.Feign.OAuth2FeignClient;
import com.xuchang.model.LoginFormVo;
import com.xuchang.model.LoginUserDto;
import com.xuchang.service.LoginService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private OAuth2FeignClient oAuth2FeignClient;
    @Value("${basic.token:Basic Y29pbi1hcGk6Y29pbi1zZWNyZXQ=}")
    private String basicToken;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 会员的登录
     *
     * @param loginForm 登录的表单参数
     * @return 登录的结果
     */
    @Override
    public LoginUserDto login(LoginFormVo loginForm, HttpServletRequest request) {
        LoginUserDto loginUser = null;
        checkFormData(loginForm,request);
        ResponseEntity<JwtToken> token = oAuth2FeignClient.getToken("password", loginForm.getUsername(), loginForm.getPassword(), "member_type", basicToken);
        if(token.getStatusCode()== HttpStatus.OK){
            JwtToken jwtToken = token.getBody();
            loginUser = new LoginUserDto(loginForm.getUsername(),jwtToken.getExpiresIn(),jwtToken.getTokenType()+" "+jwtToken.getAccessToken(),jwtToken.getRefreshToken());
            redisTemplate.opsForValue().set(jwtToken.getAccessToken(),"",jwtToken.getExpiresIn(), TimeUnit.SECONDS);
        }
        return loginUser;
    }
    /**
     * 校验数据
     * 极验证的数据校验
     *
     * @param loginForm
     */
    private void checkFormData(LoginFormVo loginForm,HttpServletRequest request) {
        System.out.printf(String.valueOf(loginForm));
        if(!CaptchaUtil.ver(loginForm.getCaptcha(),request)){
           throw new RuntimeException("验证码错误");
        }
    }
}
